<template>
  <page-meta :root-font-size="fontSizeStore.currentFontSizeRpx"></page-meta>
  <HeadNav :title="pageTitle" />
  <view class="online-supermarket">
    <view class="supermarket-layout">

      <!-- 左侧菜单 -->
      <scroll-view class="category-menu" scroll-y :scroll-into-view="leftScrollInto" scroll-with-animation>
        <view v-for="(category, index) in categories" :key="index" :id="`left-item-${index}`"
          class="category-menu__item" :class="{ 'category-menu__item--active': activeIndex === index }"
          @click="handleCategoryMenuClick(index)">
          <text class="cat_name">{{ category.name }}</text>
        </view>
      </scroll-view>

      <!-- 右侧内容 -->
      <view class="content-panel" @touchmove.stop>
        <view class="sort_view">
          <wd-sort-button :line="true" custom-class="sort_size" title="价格" v-model="priceSortValue"
            @change="priceSorthandleChange" />
          <wd-search placeholder-left hide-cancel />
        </view>


        <!-- 商品列表（修复滚动事件触发问题） -->
        <scroll-view ref="rightScrollRef" id="rightScrollView" class="content-goods__scroll" scroll-y="true"
          :scroll-into-view="targetId" scroll-with-animation @scroll="handleRightScroll">
          <view class="content-goods__container">
            <!-- 关键：确保分类标题ID与计算位置的选择器完全匹配 -->
            <view class="category-card" v-for="(category, index) in filteredCategories" :key="index"
              :id="`right-category-${index}`">
              <view class="category-card__title text12" :id="`category-title-${index}`">
                {{ category.name }}
                <span class="category-count text12">({{ category.filteredFoods.length }})</span>
              </view>

              <view v-if="category.filteredFoods.length === 0" class="no-results">
                没有找到符合条件的商品
              </view>

              <view v-for="food in category.filteredFoods" :key="food.id" class="goods-item">
                <view class="goods-item__img">
                  <image
                    :src="food.imageUrl || 'https://p0.meituan.net/coverpic/4e9b9e5a742ddfc29f9efb8c7033dbe21323862.jpg%40538w_717h_1e_1c_1l%7Cwatermark%3D0'"
                    :alt="food.name">
                  </image>
                </view>
                <view class="goods-item__info">
                  <view>
                    <text class="goods-item__name text11">{{ food.name }}</text>
                  </view>
                  <view class="goods-item__sales text11">销量: {{ food.sales }}份</view>
                  <view>
                    <text class="goods-item__price text11">￥{{ food.price }}</text>
                  </view>
                </view>


                <view v-if="qiangdan_view" class="qiangdan_view">
                  <text class="iconfont icon-cart-add" @click="handleGoodsCountChange(food, -100)"></text>
                  <text class="desc">抢单</text>
                </view>
                <view class="goods-item__count" v-if="!qiangdan_view">
                  <view v-if="food.count > 0" class="count-btn count-btn--minus text11"
                    @click="handleGoodsCountChange(food, -1)">-</view>
                  <text v-if="food.count > 0" class="count-btn__num text11">{{ food.count }}</text>
                  <view class="count-btn count-btn--plus text11" @click="handleGoodsCountChange(food, 1)">+
                  </view>
                </view>
              </view>
            </view>
            <view class="content-goods__spacer"></view>
          </view>
        </scroll-view>
      </view>
    </view>

    <!-- 底部导航 -->
    <view class="bottom-nav" v-if="!showBottomModel && !isFilterPopupOpen">
      <view class="bottom-nav__cart" @click="handleShowPaymentPopup">
        <view class="cart__wrap">
          <wd-icon name="cart" size="22px"></wd-icon>
          <view v-if="cartCount > 0" class="cart__badge" :class="{ 'cart__badge--dot': cartCount === 0 }">
            {{ cartCount > 99 ? '99+' : cartCount }}
          </view>
        </view>
        <view class="cart__text">购物车</view>
      </view>
      <view class="bottom-nav__price">
        <view class="price__content">
          <text class="price__symbol">¥</text>
          <text class="price__amount">{{ cartTotalAmount }}</text>
        </view>
        <view class="price__desc">配送费</view>
      </view>
      <view class="bottom-nav__reserve">
        <wd-button @click="actionCart" type="error" size="medium" class="reserve__btn" :disabled="cartCount === 0">
          立即预约
        </wd-button>
      </view>
    </view>


  </view>

  <!-- 删除原来的 cart_view 内容，替换为组件 -->
  <view class="payment-popup">
    <wd-action-sheet title="我的购物车" v-model="showBottomModel" @close="handleHidePaymentPopup">
      <CartListView ref="cartListViewRef" :categories="categories" @update:categories="handleCategoriesUpdate"
        @checkout="handleCartCheckout" />
    </wd-action-sheet>
  </view>



</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import Decimal from 'decimal.js'  // 引入decimal.js
import CartListView from '@/components/CartListView/index.vue'

import {
  ref,
  nextTick,
  watch,
  computed
} from 'vue'
import HeadNav from '@/components/HeadNav/index.vue'
import {
  useFontSizeStore
} from '@/stores/fontSizeStore';
import {
  jifen_chaoshiApi,
  yaodian_chaoshiApi,
  yiyuan_yuyueApi,
  bangding_shebeiApi,
  yiri_cansanApi,
  shenghuo_leiApi,
} from "@/api/products"

import {
  useRouter
} from 'uni-mini-router'

// 路由实例 - 保留原逻辑
const router = useRouter();
const qiangdan_view = ref(false)



const fontSizeStore = useFontSizeStore();


// 购物车相关状态
const cartCategories = ref([]) // 按分类整理的购物车商品

// 当前激活的Tab
const paramName = ref("")
const pageTitle = ref("")
const priceSortValue = ref(0)

const showBottomModel = ref(false);

// 滚动相关（核心修复：确保变量初始化正确）
const rightScrollRef = ref(null)
const contentPositions = ref([]) // 存储分类标题位置，滚动联动依赖此数据
const activeIndex = ref(0)
const leftScrollInto = ref('')
const targetId = ref('')

// 筛选核心状态
const isFilterPopupOpen = ref(false)


// 添加 ref
const cartListViewRef = ref(null)

// 监听弹窗打开，触发默认全选
watch(
  () => showBottomModel.value,
  (isShow) => {
    if (isShow) {
      cartListViewRef.value?.setDefaultSelectAll()
    }
  }
)

// 同步 categories 变更（可选，如果你在其他地方也修改 categories）
const handleCategoriesUpdate = (newCategories) => {
  categories.value = newCategories
}

// 结算逻辑
const handleCartCheckout = (cartData) => {
  const list = JSON.stringify(cartData)
  uni.setStorage({
    key: 'common_yuyue_key',
    data: list,
    success: () => {
      router.push({ name: "common_yuyue" })
    }
  })
}


// 商品数据
const categories = ref([])

// 计算筛选后的分类和商品
const filteredCategories = computed(() => {
  return categories.value.map(category => {
    let filteredFoods = [...category.foods].filter(food => {
      return true
    })

    return {
      ...category,
      filteredFoods
    }
  }).filter(category => category.filteredFoods.length > 0)
})

// 购物车相关
const cartCount = ref(0)
const totalAmount = ref('0.00')

const calculateCategoryPositions = async () => {
  await nextTick()
  const list = filteredCategories.value
  if (list.length === 0) return

  // 清空旧数据
  contentPositions.value = new Array(list.length).fill(null)

  // 获取滚动容器位置（#rightScrollView）
  const scrollQuery = uni.createSelectorQuery()
  scrollQuery.select('#rightScrollView').boundingClientRect()
  scrollQuery.exec(async (res) => {
    const scrollViewRect = res[0]
    if (!scrollViewRect) return

    // 遍历每个分类，获取其标题位置
    for (let index = 0; index < list.length; index++) {
      const query = uni.createSelectorQuery()
      query.select(`#category-title-${index}`).boundingClientRect()
      query.exec((rectRes) => {
        const rect = rectRes[0]
        if (rect) {
          contentPositions.value[index] = {
            top: rect.top - scrollViewRect.top,
            bottom: rect.bottom - scrollViewRect.top,
            height: rect.height
          }
        } else {
          // 如果获取失败，延迟重试
          setTimeout(() => {
            const retryQuery = uni.createSelectorQuery()
            retryQuery.select(`#category-title-${index}`)
              .boundingClientRect()
            retryQuery.exec(retryRes => {
              const r = retryRes[0]
              if (r) {
                contentPositions.value[index] = {
                  top: r.top - scrollViewRect.top,
                  bottom: r.bottom - scrollViewRect
                    .top,
                  height: r.height
                }
              }
            })
          }, 50)
        }
      })
    }
  })
}

const handleRightScroll = (e) => {
  const scrollTop = e.detail.scrollTop

  if (contentPositions.value.length === 0) return

  // 滚动到顶部时，激活第一个
  if (scrollTop <= 10) {
    if (activeIndex.value !== 0) {
      activeIndex.value = 0
      leftScrollInto.value = 'left-item-0'
    }
    return
  }

  let matchedIndex = -1
  const len = contentPositions.value.length

  // 从后往前找，找到第一个“顶部在视口内”的分类
  for (let i = len - 1; i >= 0; i--) {
    const pos = contentPositions.value[i]
    if (!pos) continue

    const isLast = i === len - 1
    // 匹配规则：当前滚动距离 >= 分类顶部 - 30px，且 < 分类底部 - 30px（或最后一个分类）
    if (scrollTop >= pos.top - 30 && (isLast || scrollTop < pos.bottom - 30)) {
      matchedIndex = i
      break
    }
  }

  // 更新左侧菜单激活状态
  if (matchedIndex !== -1 && activeIndex.value !== matchedIndex) {
    activeIndex.value = matchedIndex
    leftScrollInto.value = `left-item-${matchedIndex}`
  }
}

// 5. 修复分类点击逻辑（确保右侧滚动到对应分类）
let clickTimer = null

const handleCategoryMenuClick = async (index) => {
  // ✅ 防抖：防止频繁点击
  if (clickTimer) clearTimeout(clickTimer)
  clickTimer = setTimeout(() => {
    clickTimer = null
  }, 300)

  if (index < 0 || index >= filteredCategories.value.length) return

  activeIndex.value = index
  leftScrollInto.value = `left-item-${index}`

  await nextTick()
  targetId.value = ''
  await nextTick()
  targetId.value = `category-title-${index}`

  // 延迟触发高亮
  setTimeout(() => {
    const query = uni.createSelectorQuery()
    query.select('#rightScrollView').boundingClientRect()
    query.exec((res) => {
      const rect = res[0]
      if (rect) {
        handleRightScroll({
          detail: {
            scrollTop: rect.scrollTop
          }
        })
      }
    })
  }, 150)
}



// 7. 页面挂载时初始化位置（确保首次加载有数据）
onLoad(async (options) => {
  console.log("out options:", options)
  const name = options.name;

  paramName.value = name;
  await nextTick()
  activeIndex.value = 0
  leftScrollInto.value = 'left-item-0'
  targetId.value = ''

  await nextTick()
  targetId.value = 'category-title-0'

  if (cartListViewRef.value && typeof cartListViewRef.value.setDefaultSelectAll === 'function') {
    cartListViewRef.value.setDefaultSelectAll()
  }




  let res = {};
  /*
    jifen_chaoshiApi,
  yaodian_chaoshiApi,
  yiyuan_yuyueApi,
  bangding_shebeiApi,
  yiri_cansanApi,
  shenghuo_leiApi,
  */
  pageTitle.value = options.title || ""
  if (name == 'jifen_chaoshi') {
    res = await jifen_chaoshiApi();
    // "积分超市"
  } else if (name == 'yaodian_chaoshi') {
    res = await yaodian_chaoshiApi();
    // pageTitle.value = "医疗超市"
  } else if (name == 'yiyuan_yuyue') {
    res = await yiyuan_yuyueApi();
    // pageTitle.value = "医院预约"
  } else if (name == 'bangding_shebei') {
    res = await bangding_shebeiApi();
    // pageTitle.value = "绑定设备"
  } else if (name == 'yiri_cansan') {
    res = await yiri_cansanApi();
    // pageTitle.value = "一日三餐"
  } else if (name == 'shenghuo_lei') {
    res = await shenghuo_leiApi();
    // pageTitle.value = "生活类"
  } else if (name == 'qiangdan') {
    res = await shenghuo_leiApi();
    // pageTitle.value = "抢单"
    qiangdan_view.value = true;
  }

  if (res?.code == 200) {
    res.data.forEach((i) => {
      i.foods.forEach((k) => {
        k.count = 0;
      })
    })
    categories.value = res.data;
    // ✅ 关键：更新 cartCategories
    updateCartCategories()

    // 延迟计算位置
    setTimeout(() => calculateCategoryPositions(), 200)
  }

})



const handleGoodsCountChange = (food, delta) => {
  console.log(food, '勾选的商品数据:', cartCategories.value)
  if (delta == -100) {
    if (cartCategories.value == 0 || cartCategories.value == undefined) {
      delta = 1
    }
  }
  if (food.count + delta < 0) return;

  food.count += delta;

  let count = 0;
  let total = new Decimal(0); // 初始化为 0

  categories.value.forEach(cat => {
    cat.foods.forEach(f => {
      count += f.count;
      // ✅ 修复：必须将 plus 的结果重新赋值给 total
      total = total.plus(new Decimal(f.price || 0).times(f.count));
    });
  });

  cartCount.value = count;
  totalAmount.value = total.toFixed(2); // 转为字符串，保留两位小数
  // ✅ 关键：更新 cartCategories
  updateCartCategories()
};



const handleShowPaymentPopup = () => {
  showBottomModel.value = true
}

const handleHidePaymentPopup = () => {
  showBottomModel.value = false
}

const priceSorthandleChange = ({ value }) => {
  console.log(value)
}

const cartTotalAmount = computed(() => {
  // 直接复用计算好的totalAmount，避免重复运算
  return totalAmount.value || '0.00'
})


// 根据 categories 自动生成 cartCategories（仅包含 count > 0 的商品）
const updateCartCategories = () => {
  const result = []
  categories.value.forEach(category => {
    const goodsInCart = category.foods.filter(food => food.count > 0)
    if (goodsInCart.length > 0) {
      result.push({
        id: category.id || category.name,
        name: category.name,
        goods: goodsInCart.map(food => ({ ...food })) // 浅拷贝，避免引用问题
      })
    }
  })
  cartCategories.value = result
}

const actionCart = () => {
  if (cartCategories.value.length === 0) {
    uni.showToast({ title: '购物车为空', icon: 'none' })
    return
  }
  // handleSelectAll();
  const data = JSON.stringify(cartCategories.value)
  uni.setStorage({
    key: 'cartCategories_data',
    data: data,
    success: function () {
      router.push({
        name: "common_yuyue"
      })
    }
  });

  // uni.setStorageSync("common_yuyue",)
}

</script>

<style lang="less" scoped>
@import url("@/static/styles/family/onlineSupermarket/index.less");


.cat_name {
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}



.sort_view {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  padding-left: 20rpx;
}

/deep/ .wd-sort-button__left {
  font-size: 1.2rem !important;
}


/deep/ .wd-sort-button__right {
  font-size: 16px;
}

.qiangdan_view {
  display: inline-flex;
  align-items: center;
  height: 56rpx;
  border-radius: 28rpx; // 外层容器圆角（可选，用于整体 hover 效果）
  overflow: hidden; // 确保子元素圆角不溢出
  background-color: #ff9900;
}

.qiangdan_view .iconfont {
  display: flex;
  align-items: center;
  justify-content: center;
  // width: 36rpx;
  // padding: 0 20rpx;
  padding-left: 20rpx;
  padding-right: 12rpx;
  height: 36rpx;
  border-radius: 50%;
  background-color: #ff9900;
  color: #ffffff;
  margin-right: -1rpx; // 微调，避免间隙
  z-index: 1;
  font-size: 20px;
}

.qiangdan_view .desc {
  display: block;
  font-size: 24rpx;
  font-weight: bold;
  color: #ffffff;
  background-color: #ff4d4f; // 红色背景
  padding: 0 14rpx;
  padding-right: 15rpx;
  padding-left: 10rpx;
  height: 100%;
  line-height: 56rpx;
  // ✅ 关键：左边直角，右边圆角
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
  border-top-right-radius: 28rpx;
  border-bottom-right-radius: 28rpx;
}
</style>